Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

316
Views
¿Cómo obtener el accesorio "clave" del elemento React (al cambiar)?

Quiero obtener el valor y la clave de la opción cuando seleccione onChange .

Sé que puedo obtener la simplicidad del valor de la opción utilizada event.target.value en la función onChangeOption , pero ¿cómo puedo obtener key ?

 <select onChange={this.onChangeOption} value={country}> {countryOptions.map((item, key) => <option key={key} value={item.value}> {item.name} </option> )} </select>
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Deberá pasar el valor en la clave como un accesorio diferente.

De documentos:

Las claves sirven como una pista para Reaccionar, pero no se pasan a sus componentes. Si necesita el mismo valor en su componente, páselo explícitamente como accesorio con un nombre diferente:

Leer: https://reactjs.org/docs/lists-and-keys.html

over 4 years ago · Santiago Trujillo Report

0

Pasar la clave como accesorio funciona obviamente, pero una forma mucho más rápida podría ser incluir la clave como un atributo personalizado en su html.

 class App extends React.Component { constructor(props) { super(props); this.onSelect = this.onSelect.bind(this); } onSelect(event) { const selectedIndex = event.target.options.selectedIndex; console.log(event.target.options[selectedIndex].getAttribute('data-key')); } render() { return ( <div> <select onChange = {this.onSelect}> <option key="1" data-key="1">One</option> <option key="2" data-key="2">Two</option> </select> </div> ); } } ReactDOM.render( < App / > , document.getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>

over 4 years ago · Santiago Trujillo Report

0

Imagina un componente como este:

 <Component data={[{id:'a23fjeZ', name="foo"}, ...]}`

Lo que representa una lista de entradas y entra en un accesorio de data que es una colección ( matriz de objetos ):

 function Component ( props ){ // cached handler per unique key. A self-invoked function with a "cache" object const onChange = (cache => param => { if( !cache[param] ) cache[param] = e => console.log(param, e.target.name, e.target.value) return cache[param]; } )({}); return props.data.map(item => <input key={item.id} name={item.name} onChange={onChange(item.id)} /> } }

Como puede ver, no se accede a la key , pero se pasa a una función de curry que maneja el almacenamiento en caché internamente, para evitar la creación "infinita" de funciones en las re-renderizaciones.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!